import
QQMapWX
from '../../../libs/qqmap-wx-jssdk.min'
// import Schema from 'async-validator'
import Schema from 'async-validator'
import {
  toast
} from '../../../../../utils/extendApi'
import {
  addAddress,
  getAddressDetail,
  updateAddress
} from '../../../api/address'

Page({
  // 页面的初始数据
  data: {
    name: "", //收货人
    phone: "", //手机号码
    provinceName: "", //省
    provinceCode: "", //省编码
    cityName: "", //市
    cityCode: "", //市编码
    districtName: "", //区
    districtCode: "", //区编码
    address: "", //详细地址
    fullAddress: "", //完整地址
    isDefault: false, //设置默认地址，0：非默认，1：默认
    id: null

  },

  // 保存收货地址
  async saveAddrssForm(event) {
    const {
      provinceName,
      cityName,
      districtName,
      address,
      isDefault
    } = this.data
    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0
    }

    const res = await this.validatorAddress(params)
    if (!res.validateRes) return
    // console.log(params);
    let tit = ''
    if (this.data.id) {
      tit = '更新'
      await updateAddress(params)
    } else {
      tit = '新增'
      await addAddress(params)
    }

    toast({
      title: tit + '地址成功',
      icon: 'success'
    })
    wx.navigateBack()
  },

  // 收货地址表单校验
  validatorAddress(params) {
    // 验证收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    // 验证手机号，是否符合中国大陆手机号码的格式
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    // 校验规则
    const rules = {
      name: [{
          require: 'true',
          message: '姓名不能为空'
        }, {
          pattern: nameRegExp,
          message: '姓名不合法'
        },
        {
          min: 3,
          max: 4,
          message: '姓名长度应在3到4位'
        }
      ],
      phone: [{
        require: 'true',
        message: '手机号不能为空'
      }, {
        pattern: phoneReg,
        message: '手机号不合法'
      }],
      provinceName: [{
        require: 'true',
        message: '所在地区不能为空'
      }],
      address: [{
        require: 'true',
        message: '详细地址不能为空'
      }]
    }
    const validator = new Schema(rules)
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          toast({
            title: errors[0].message,
            icon: 'error'
          })
          resolve({
            validateRes: false
          })
        } else {
          resolve({
            validateRes: true
          })
        }
      })
    })

  },
  // 省市区选择
  onAddressChange(event) {

    const [provinceCode, cityCode, districtCode] = event.detail.code
    const [provinceName, cityName, districtName] = event.detail.value
    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode
    })
  },
  // 打开地图选择位置
  async chooseLoction() {
    // 解构出经度和纬度
    const {
      latitude,
      longitude,
      name
    } = await wx.chooseLocation()
    // 调用reverseGeocoder方法，获取地理位置信息和附近poi列表。
    this.qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      // 逆解析成功调用
      success: (res) => {
        // 因无法获取配置额度，功能未完善....

        const {
          result: {
            ad_info
          }
        } = res
        console.log(ad_info);
      }
    })
  },
  // 获取收货地址详情
  async getAddressDetail(id) {
    const {
      data: {
        name,
        cityCode,
        cityName,
        districtCode,
        fullAddress,
        isDefault,
        phone,
        provinceCode,
        provinceName,
        districtName,
        address

      }
    } = await getAddressDetail(id)


    this.setData({
      name,
      phone,
      provinceName,
      provinceCode,
      cityName,
      cityCode,
      districtName,
      districtCode,
      address,
      fullAddress,
      isDefault: isDefault === 1 ? true : false
    })
  },

  onLoad({
    id
  }) {
    // 实例化API核心类
    this.qqmapsdk = new QQMapWX({
      key: 'M6LBZ-PGH6Z-HIPXG-742FN-6MTI5-63FLP'
    })
    if (id) {
      this.setData({
        id
      })
      this.getAddressDetail(id)
    }

  }
})